package com.ljc.chatroom.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
/**
 * @author: luojiacheng
 * @create: 2019/12/12 13:12
 * @description: WebSocket自定义Handler
 */

//问题：如何将username和channel绑定？
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        System.out.println("channelRead0 invoked");
        //获取到当前的channel对象
        Channel channel = ctx.channel();

        channelGroup.forEach(ch ->{
            if(channel != ch){
                ch.writeAndFlush(new TextWebSocketFrame("【"+textWebSocketFrame.text().split(":")[0]+"】 ："+textWebSocketFrame.text().split(":")[1]));
            }else{
                //如果是自己发送的消息
                ch.writeAndFlush(new TextWebSocketFrame("【自己】："+textWebSocketFrame.text().split(":")[1]));
            }
        });
    }

    //用户重新激活
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(new TextWebSocketFrame(ctx.channel().remoteAddress()+"上线了！"));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(new TextWebSocketFrame(ctx.channel().remoteAddress()+"下线了！"));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerAdded invoked!");
        Channel channel = ctx.channel();

        //广播消息
        //会循环调用channel的writeAndFlush方法
        channelGroup.writeAndFlush(new TextWebSocketFrame("[服务器] - "+channel.remoteAddress()+"加入"));
        channelGroup.add(channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush(new TextWebSocketFrame("[服务器] -"+ channel.remoteAddress() +"离开"));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
